package com.easy.admin.system.test.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 *
 * @author wangbo
 * @deprecated netty client for chat
 */

public class ChatClient {

    private String ip;

    private int port;

    public ChatClient(String ip,int port){
        this.ip=ip;
        this.port = port;
    }

    public void run() {

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        Channel channel = null;
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline ch = socketChannel.pipeline();
                            ch.addLast("decoder", new StringDecoder());//解码器
                            ch.addLast("encoder", new StringEncoder());//编码器
                            ch.addLast(new ChatClientHandler());
                        }
                    });

            ChannelFuture  cf = bootstrap.connect(this.ip, this.port).sync();
             channel = cf.channel();
            Scanner sc = new Scanner(System.in);
            while (sc.hasNextLine()) {
                String content = sc.nextLine();
                channel.writeAndFlush(content);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
            channel.closeFuture();
        }
    }
}
